/*
' Copyright (c) 2014  Diadrasis
'  All rights reserved.
' 
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
' DEALINGS IN THE SOFTWARE.
' 
*/

using System;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Security;
using net.diadrasis.dnn.jsImageGallery.Components;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Common;

using System.Web.Script.Serialization;

//include to import js file
//you will also have to inlcude a couple of references liks
//System.Web - DotNetNuke.Web.Client - ClientDependency.Core etc...
using DotNetNuke.Web.Client.ClientResourceManagement;
using System.Web;
using System.Web.UI;
using System.Collections;
using System.Collections.Generic;
using DotNetNuke.Services.FileSystem;





namespace net.diadrasis.dnn.jsImageGallery
{

    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The View class displays the content
    /// 
    /// Typically your view control would be used to display content or functionality in your module.
    /// 
    /// View may be the only control you have in your project depending on the complexity of your module
    /// 
    /// Because the control inherits from jsImageGalleryModuleBase you have access to any custom properties
    /// defined there, as well as properties from DNN such as PortalId, ModuleId, TabId, UserId and many more.
    /// 
    /// </summary>
    /// -----------------------------------------------------------------------------
    public partial class View : jsImageGalleryModuleBase, IActionable
    {
        //to read from javascript must be public!!!
        //the old way!
        public string moduleName;
        public string hostURL;
        public string json;
        public string json2;
        public List<cImage> lst = new List<cImage>();
        public List<cImageSection> seclst = new List<cImageSection>();
        public List<List<cImage>> secimglst = new List<List<cImage>>();
        public int showTime; //default value
        public int puzzleItemsHor;
        public int puzzleItemsVer;
        public bool puzzleEffect;
        public string imgRatio;
        public string initImage;
        
        
        #region Event Handlers

        override protected void OnInit(EventArgs e)
        {
           
            
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
        }


        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// -----------------------------------------------------------------------------
        /// 
        
        private void Page_Load(object sender, System.EventArgs e)   {           
                
                    try
                    {

                        if (!Page.IsPostBack)
                        {    
                            //read the current div to show the images; 
                            if (Settings["modulePosition"] != null)
                            {
                                if (Settings["modulePosition"].ToString() == "in media module")
                                {
                                    moduleName = "MediaPane";
                                }
                                else
                                {
                                    moduleName = "dnn_ctr" + ModuleId.ToString() + "_ModuleContent";
                                }
                            }
                            else
                            {
                                moduleName = "dnn_ctr" + ModuleId.ToString() + "_ModuleContent";
                            }

                            //pass this to js
                            hostURL = Globals.NavigateURL();
                             
                            //read this from settings to select the fade mode                            
                            if (Settings["jsFile1"] != null){
                                this.DnnJsInclude1.FilePath = "~/DesktopModules/jsImageGallery/" + "js/" + Settings["jsFile1"].ToString();
                            } else{
                                this.DnnJsInclude1.FilePath = "~/DesktopModules/jsImageGallery/js/fadeImages.js";
                            }

                            if (Settings["showTime"] != null){
                                this.showTime = Convert.ToInt16(Settings["showTime"])*60;
                            } else {
                                this.showTime = 4*60;
                            }
                            
                            if (Settings["puzzleItemsVert"] != null){
                                this.puzzleItemsVer = Convert.ToInt16(Settings["puzzleItemsVert"]);
                            } else {
                                this.puzzleItemsVer = 1;
                            }

                            if (Settings["puzzleItemsHoriz"] != null){
                                this.puzzleItemsHor = Convert.ToInt16(Settings["puzzleItemsHoriz"]);
                            } else {
                                this.puzzleItemsHor = 1;
                            }


                            if (Settings["puzzleEffect"] != null){
                                this.puzzleEffect = Convert.ToBoolean(Settings["puzzleEffect"]);
                            } else {
                                this.puzzleEffect = false;
                            }

                            if (Settings["imageRatio"] != null) {
                                this.imgRatio = Settings["imageRatio"].ToString();
                            } else {
                                this.imgRatio = "2.5";
                            }

                            /*
                            if (Settings["initImage"].ToString() != null) {
                                this.initImage = FindImagePath(Settings["initImage"].ToString());
                            } else {
                                this.initImage = "";
                            }
                            */
                            
                            //read images
                            seclst = cImageSectionController.GetImageSections(ModuleId);
                            foreach (cImageSection imgsec in seclst){
                                List<cImage> imglst = new List<cImage>();
                                imglst = cImageController.GetSectionImages(imgsec.id);
                                foreach (cImage img in imglst){
                                    img.file = FindImagePath(img.file);
                                }
                                secimglst.Add(imglst);
                            }



                            json = new JavaScriptSerializer().Serialize(secimglst);                                                 
                         
                           
                            //do it with string builder like that
                            /*
                            StringBuilder cstext2 = new StringBuilder();
                            cstext2.Append("<script type=\"text/javascript\"> function DoClick() {");
                            cstext2.Append("Form1.Message.value='Text from client script.'} </");
                            cstext2.Append("script>");
                            */
                           
                            
                            //this block defines the javascrip variable myJson2 to be available in the javascript code
                            Type cstype = this.GetType();
                            ClientScriptManager cs = Page.ClientScript;
                            string script = string.Format("var myJson = '{0}';", json); 
                            if (!cs.IsClientScriptBlockRegistered(cstype, "myScript")) {
                                cs.RegisterClientScriptBlock(cstype, "myScript", script, true);
                            }                           
                        }
                    }  catch (Exception exc) //Module failed to load
                    {
                        Exceptions.ProcessModuleLoadException(this, exc);
                    }
                
        
        }

        protected string FindImagePath(string dnnImgID)
        {
            int id = Convert.ToInt32(dnnImgID.Substring(7));
            FileInfo imgInfo = (FileInfo)FileManager.Instance.GetFile(id);
            string url = PortalSettings.HomeDirectory + imgInfo.Folder + imgInfo.FileName;
            return url;
        }
       

        #endregion

        #region Optional Interfaces

        public ModuleActionCollection ModuleActions
        {
            get
            {
                ModuleActionCollection Actions = new ModuleActionCollection();
                Actions.Add(GetNextActionID(), Localization.GetString("EditModule", this.LocalResourceFile), "", "", "", EditUrl(), false, SecurityAccessLevel.Edit, true, false);
                return Actions;
            }
        }

        #endregion

      

       

       

       

    }

}
